from django.core.management.base import BaseCommand
from django.utils import timezone
from datetime import timedelta, datetime
from django.db.models import Sum, F, Q
from django.db import transaction
from crawler.models import BetRecord, UserProfile


class Command(BaseCommand):
    help = '结算每日流水奖励'

    def handle(self, *args, **options):
        today = timezone.now().date()
        start = timezone.make_aware(datetime(today.year, today.month, today.day))
        end = start + timedelta(days=1)

        self.stdout.write(f"结算日期范围：{start} 至 {end}")

        with transaction.atomic():
            # 用户个人奖励（只处理已封盘结算的未处理记录）
            user_bets = BetRecord.objects.filter(
                Q(created_at__range=(start, end)) &
                Q(is_cancelled=False) &
                Q(result__isnull=False) &  # 新增：必须完成封盘结算
                Q(is_settled=False)        # 未结算过的记录
            ).values('user').annotate(total=Sum('amount'))

            self.stdout.write(f"个人流水记录数：{len(user_bets)}")
            for entry in user_bets:
                self.stdout.write(f"更新用户 {entry['user']}，增加积分 {entry['total'] * 0.02}")
                UserProfile.objects.filter(user_id=entry['user']).update(
                    score=F('score') + entry['total'] * 0.02
                )

            # 邀请人奖励
            invitee_bets = BetRecord.objects.filter(
                created_at__range=(start, end),
                is_cancelled=False,
                is_settled=False,  # 新增过滤条件
                user__profile__inviter__isnull=False
            ).values('user__profile__inviter').annotate(total=Sum('amount'))

            self.stdout.write(f"邀请人流水记录数：{len(invitee_bets)}")
            for entry in invitee_bets:
                self.stdout.write(f"更新邀请人 {entry['user__profile__inviter']}，增加积分 {entry['total'] * 0.005}")
                UserProfile.objects.filter(user_id=entry['user__profile__inviter']).update(
                    score=F('score') + entry['total'] * 0.005
                )
            BetRecord.objects.filter(
                created_at__range=(start, end),
                is_cancelled=False
            ).update(is_settled=True)

        self.stdout.write(f"成功结算 {today} 的流水奖励")